package com.itheima.reggie.config;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 编写登录过滤器
 */

@Slf4j
// @WebFilter(urlPatterns = "/*",filterName = "loginFilter")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("login interceptor takes effect..");
    }

    @Override
    public void destroy() {
        log.info("login interceptor destroy..");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //强转Servlet类型 -> HttpServlet
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断本次请求是否需要处理 如果是请求登录资源则放行
        if (request.getRequestURI().contains("/login")) {
            chain.doFilter(request,response);   //放行请求
            return;
        }

        //拿到session中的attribute
        HttpSession session = request.getSession();
        if ((null != session.getAttribute("employee") )) {
            chain.doFilter(request,response);
            return;
        }

        //未登录，返回未登录结果(使用请求输出流的方法)
        response.getWriter().write(JSON.toJSONString(resNotLoginMessage()));

    }

    private R<String> resNotLoginMessage() {
        R<String> r = new R<>();
        r.setCode(0);
        r.setMsg("NOTLOGIN");
        return r;
    }
}
